const postsModel=require('../model/posts')

// 所有文章
module.exports = {
    getPostsPage(req, res) {
        // if (req.session.isLogin) {
            res.render('admin/posts');
        // } else {
            // res.send('<script>location.href="http://127.0.0.1:8080/admin/user/login.html"</script>');
        // }
    },
    getAllPosts(req, res) {
        postsModel.getAllPosts(data=>{
            // console.log(data);
            let response=data?{code:200,msg:'获取成功',data}:{code:500,msg:'获取失败'};
            res.send(response);
        });
    },
    getPostsByPage(req,res){
        let {pageIndex,pageSize}=req.query;
        postsModel.getPostsByPage(pageIndex, pageSize,data=>{
            // console.log(data);
            let response=data instanceof Array?{code:200,msg:'获取成功',data}:{code:500,msg:'获取失败'};
            postsModel.getPostCount(result=>{
                result ? response.total = Math.ceil(result.total/pageSize) :'';
                res.send(response)
            })
        })
    },
    getPostsByFilter(req, res) {
        let{category,status,pageIndex,pageSize}=req.query;
        let sql = `SELECT
    posts.id,posts.title,posts.created,posts.\`status\`,
    categories.\`name\`,
    users.nickname
   FROM posts
  LEFT JOIN categories ON posts.category_id = categories.id
  LEFT JOIN users ON posts.user_id = users.id`;
        let condition=` WHERE 1=1 `
        if(category!=0){
            condition += ` AND category_id='${category} '`
        }
        if(status!='all'){
            condition+=` AND posts.\`status\`='${status} '`
        }
        let pageQuery = ` LIMIT ${(pageIndex - 1) * pageSize},${pageSize} `
        // console.log(sql + condition);
        postsModel.getPostsByFilter(sql + condition + pageQuery, data => {             
            // console.log(data);
            let response =data?{code:200,msg:'筛选成功',data}:{code:500,msg:'筛选失败'};            
            postsModel.getPostCountByFilter(condition,result=>{
                response.total = Math.ceil(result.total / pageSize)
                res.send(response);
            })
        });
    },
    deletePostsById(req,res){
        let {id}=req.query;
        // console.log(id);
        postsModel.deletePostsById(id,result=>{
            // console.log(result);
           let respons = result.affectedRows===1?{code:200,msg:'ok'}:{code:500,msg:'失败'};
            res.send(respons);
        })
    },
    deletePostByMutiple(req,res){
        let {ids}=req.query;
        // console.log(ids);
        postsModel.deletePostByMutiple(ids,result=>{
            // console.log(result);
            let response=result.affectedRows==ids.length?{code:200,msg:'删除成功'}:{code:500,msg:'删除失败'};
            res.send(response);
        })
    }
}